package cn.xinfei.xdecision.datasource.mysql.dynamic;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

@Slf4j
@Service
@Order(Integer.MAX_VALUE)
@ConditionalOnProperty(name = "spring.datasource.druid.data.enable")
public class DynamicDatasourceApplicationCallback implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    @Qualifier("druidDataSourceData")
    public DruidDataSource druidDataSourceData;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        log.info("==========ApplicationReadyEvent===DynamicDatasourceApplicationCallback================");
        try {
            druidDataSourceData.init();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
